package edu.guigu.appquickstart.datastore.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.util.List;

/**
 * 本类是一个SQLite基础封装类，提供了基本的CRUD操作，并支持事务处理
 *
 * @author yuanc
 * @Description: (用一句话描述)
 * @date 2025/8/12 20:14
 */
public class DBHelper extends SQLiteOpenHelper {
    private static final String TAG = "DatabaseHelper";
    private static final String DATABASE_NAME = "app_database.db";
    private static final int DATABASE_VERSION = 1;

    private static DBHelper instance;
    private SQLiteDatabase db;

    // 私有构造方法
    private DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        db = getWritableDatabase();
    }

    // 单例模式获取实例
    public static synchronized DBHelper getInstance(Context context) {
        if (instance == null) {
            instance = new DBHelper(context.getApplicationContext());
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // 创建用户表的SQL语句
        final String CREATE_USERS_TABLE = "CREATE TABLE  IF NOT EXISTS " + IUserDao.TABLE_USERS + "("
                + IUserDao.COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + IUserDao.COLUMN_USERNAME + " TEXT NOT NULL UNIQUE,"
                + IUserDao.COLUMN_EMAIL + " TEXT,"
                + IUserDao.COLUMN_PHONE + " TEXT,"
                + IUserDao.COLUMN_AGE + " INTEGER,"
                + IUserDao.COLUMN_REGISTER_TIME + " DATETIME DEFAULT CURRENT_TIMESTAMP"
                + ")";
        // 创建表
        db.execSQL(CREATE_USERS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 数据库升级逻辑
        db.execSQL("DROP TABLE IF EXISTS " + IUserDao.TABLE_USERS);
        onCreate(db);
    }

    // 插入数据
    public long insert(String table, ContentValues values) {
        return db.insert(table, null, values);
    }

    // 批量插入数据
    public void bulkInsert(String table, List<ContentValues> valuesList) {
        db.beginTransaction();
        try {
            for (ContentValues values : valuesList) {
                db.insert(table, null, values);
            }
            db.setTransactionSuccessful();
        } catch (Exception e) {
            Log.e(TAG, "批量插入数据失败", e);
        } finally {
            db.endTransaction();
        }
    }

    // 查询数据
    public Cursor query(String table, String[] columns, String selection,
                        String[] selectionArgs, String groupBy, String having,
                        String orderBy) {
        return db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
    }

    // 查询所有数据
    public Cursor queryAll(String table) {
        return db.query(table, null, null, null, null, null, null);
    }

    // 更新数据
    public int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
        return db.update(table, values, whereClause, whereArgs);
    }

    // 删除数据
    public int delete(String table, String whereClause, String[] whereArgs) {
        return db.delete(table, whereClause, whereArgs);
    }

    // 执行SQL语句
    public void execSQL(String sql) {
        db.execSQL(sql);
    }

    // 执行带参数的SQL语句
    public void execSQL(String sql, Object[] bindArgs) {
        db.execSQL(sql, bindArgs);
    }

    // 关闭数据库
    public void closeDB() {
        if (db != null && db.isOpen()) {
            db.close();
        }
        instance = null;
    }
}